<?php

namespace app\admin\model;

use app\api\service\CommonService;
use app\common\model\Alipay;
use app\common\model\Export;
use app\model\Agent;
use app\model\AgentBalanceLog;
use app\model\AgentWithdraw as Model;
use think\facade\Db;

/**
 * 代理商提现.
 */
class Withdraw extends CommonService
{
    private $table = 'agent_withdraw';

    public function getList($params)
    {
        $paginate = [
            'page' => $params['page'] ?? 1,
            'list_rows' => $params['list_rows'] ?? 10,
        ];

        $modelQuery = Model::withJoin(['agent' => function ($query) {
            $query->field(['id', 'company_name', 'username','merchat_id'])
                ->WithField(['agent.company_name' => 'company_name', 'agent.username' => 'username']);
        }])->with('agentExtend');
        if (!empty($params['keyword'])) {
            $modelQuery = $modelQuery->where('agent.username|agent.company_name|agent_withdraw.alipay|agent_withdraw.wechat|agent_withdraw.mobile', 'like', '%' . $params['keyword'] . '%');
        }
        if (!empty($params['status'])) {
            $modelQuery = $modelQuery->where($this->table . '.status', $params['status']);
        }
        if (!empty($params['from'])) {
            $modelQuery = $modelQuery->where($this->table . '.from', $params['from']);
        }
        if (!empty($params['type'])) {
            $modelQuery = $modelQuery->where($this->table . '.type', $params['type']);
        }
        if (!empty($params['startValue'])) {
            $modelQuery = $modelQuery->where($this->table . '.created_at', '>=', $params['startValue']);
        }
        if (!empty($params['endValue'])) {
            $modelQuery = $modelQuery->where($this->table . '.created_at', '<=', $params['endValue'] . ' 23:59:59');
        }

        if (empty($params['is_export'])) {
            $list = $modelQuery->order($this->table . '.id desc')->paginate($paginate);
        } else {
            $stateArr = Model::$status;
            $list = $modelQuery->order($this->table . '.id desc')->select()->toArray();
            $res = [];
            if (!isset($params['type']) || $params['type'] == 1) {
                // 支付宝提现
                $title = ['提现方式', '代理商名称', '公司名称', '申请金额', '支付宝', '微信', '联系手机', '提现状态', '申请时间', '用户备注', '审核备注','后台'];
                foreach ($list as $v) {
                    $from = $v['from']==1?'后台':'有美生活';
                    $res[] = [
                        '支付宝',
                        $v['username'],
                        $v['company_name'],
                        fen2yuan($v['amount']) . '',
                        $v['alipay'],
                        $v['wechat'],
                        $v['mobile'],
                        $stateArr[$v['status']] ?? '申请中',
                        $v['created_at'],
                        $v['user_remark'],
                        $v['remark'],
                        $from
                    ];
                }
                $name = '支付宝提现列表';
            } else {
                // 银行卡提现
                $title = ['提现方式', '代理商名称', '公司名称', '申请金额', '银行卡号', '户名', '开户行', '联系手机', '提现状态', '申请时间', '用户备注', '审核备注','后台'];
                foreach ($list as $v) {

                    $from = $v['from']==1?'后台':'有美生活';
                    $res[] = [
                        '银行卡',
                        $v['username'],
                        $v['company_name'],
                        fen2yuan($v['amount']) . '',
                        $v['bank_card_no'],
                        $v['bank_username'],
                        $v['bank_name'],
                        $v['mobile'],
                        $stateArr[$v['status']] ?? '申请中',
                        $v['created_at'],
                        $v['user_remark'],
                        $v['remark'],
                        $from
                    ];
                }
                $name = '银行卡提现列表';
            }
            unset($list);
            $export = new Export;
            return $export->downloadExcel($title, $res, $name);
        }

        if (!$list->isEmpty()) {
            $list = $list->hidden(['agent']);
        }
        $list = $list->toArray();
        $list['total_apply_amount'] = $modelQuery->sum('amount');
        $list['total_success_amount'] = $modelQuery->whereIn($this->table . '.status', [2, 6])->sum('amount');
        /*
        $list['total_apply_amount'] = Db::name('agent_withdraw')
            // ->where('status', '!=', 4)
            ->sum('amount');
        $list['total_success_amount'] = Db::name('agent_withdraw')
            ->whereIn('status', [2, 6])
            ->sum('amount');
        */

        return $list;
    }

    /**
     * 审核通过.
     */
    public function accept($id)
    {
        $model = Model::where('status', 1)->find($id);
        if (!$model) {
            return $this->inValiReturn('申请不存在');
        }
        $model->status = 2;
        if (!$model->save()) {
            return $this->inValiReturn('操作失败');
        }

        // $this->doWithdraw($model);

        return $this->valiReturn();
    }

    /**
     * 审核不通过.
     */
    public function reject($params)
    {
        $info = Model::where('status', 1)->find($params['id']);
        if (!$info) {
            return $this->inValiReturn('申请不存在');
        }

        Db::startTrans();
        try {
            Db::name($this->table)
                ->where('id', $params['id'])
                ->update([
                    'status' => 3,
                    'remark' => $params['remark'],
                ]);
            $profitBalance = Db::name('agent')
                ->where('id', $info['agent_id'])
                ->lock(true)
                ->value('profit_balance');
            Db::name('agent')
                ->where('id', $info['agent_id'])
                ->inc('profit_balance', $info['amount'])
                ->update([
                    'balance_last_updated_at' => date('Y-m-d H:i:s'),
                ]);
            Db::name('agent_balance_log')
                ->insert([
                    'agent_id' => $info['agent_id'],
                    'type' => BALANCE_WITHDRAW_REJECT,
                    'amount' => $info['amount'],
                    'old_balance' => $profitBalance,
                    'new_balance' => $profitBalance + $info['amount'],
                    'remark' => '拒绝提现申请 ' . fen2yuan($info['amount']) . ' 元',
                    'quote_id' => $info['id'],
                ]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return $this->inValiReturn($e->getMessage());
        }

        return $this->valiReturn();
    }

    /**
     * todo 提现成功打款
     */
    public function doWithdraw($model)
    {
        $cacheKey = 'agentWithdraw_' . $model->id;
        if (cache($cacheKey)) {
            return $this->valiReturn('已经提现成功，数据尚未更正，请联系我们');
        }
        $transerRes = 0;
        try {
            $data = [
                'out_biz_no' => $model->id,
                'trans_amount' => fen2yuan($model->real_price),  // 实际为扣除手续费后的金额
                'product_code' => 'TRANS_ACCOUNT_NO_PWD',
                'biz_scene' => 'DIRECT_TRANSFER',
                'order_title' => '提现',
                'payee_info' => [
                    'identity' => $model->alipay,  // 参与方的唯一标识
                    'identity_type' => 'ALIPAY_LOGON_ID', // 1、ALIPAY_USER_ID 支付宝的会员ID  2、ALIPAY_LOGON_ID：支付宝登录号，支持邮箱和手机号格式
                ],
            ];

            $transerRes = Alipay::make(0)->transfer($data);
        } catch (\Exception $e) {
            doLog(getExceptionMsg($e));
        }

        if ($transerRes) { //退款成功
            $refundState = 5;
            $remark = '提现成功';
        } else {
            $refundState = 6;
            $remark = '退款成功';
        }

        $model->state = $refundState;
        Db::startTrans();
        try {
            $model->save();
        } catch (\Exception $e) {
            doWarning($remark . getExceptionMsg($e));
            if ($transerRes) {
                // todo 做警报
                cache($cacheKey, 1, 86400); //已经退款成功但是数据库操作失败的，加个锁定

                return $this->valiReturn();
            }

            return $this->inValiReturn('提现失败，请重试或者联系我们');
        }
    }
}
